package com.jzo2o.health.listener;

import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.JsonUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {

    @Resource
    private IOrdersService ordersService;

    /**
     * 更新支付结果
     *
     * @author XingDong
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_TRADE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        log.info("接收到支付结果状态的消息 ({})-> {}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);
        // 遍历list集合，判断交易是否是health，即health服务
        List<TradeStatusMsg> list = JsonUtils.toList(msg, TradeStatusMsg.class);
        for (TradeStatusMsg tradeStatusMsg : list) {
            if (ObjectUtils.equals(tradeStatusMsg.getProductAppId(), TradeConstants.PRODUCT_APP_ID)
                    && ObjectUtils.equals(TradingStateEnum.YJS.getCode(), tradeStatusMsg.getStatusCode())) {
                // 如果是health服务的直接处理支付成功的消息
                ordersService.paySuccess(tradeStatusMsg);
            }
        }
    }
}
